﻿Imports System.Text
Imports System.Security
Imports System.Security.Cryptography
Imports Meiners.Libs.Withings.Core

''' <summary>
''' Represents a withings account with mutiple users
''' </summary>
''' <remarks></remarks>
Public Class Account

    Private m_emailAddress As String
    Private m_password As String
    Private m_computedHash As String

    Private Function ComputeHash() As String
        Dim magicString As String
        Dim passwordHash As String
        Dim emailPasswordCombination As String

        Dim target As WBSAPIConnector = New WBSAPIConnector
        magicString = target.GetMagicStringForHash()

        passwordHash = getMD5Hash(m_password)

        emailPasswordCombination = String.Format(System.Globalization.CultureInfo.CurrentCulture, _
                                                 "{0}:{1}:{2}", _
                                                 New Object() {m_emailAddress, passwordHash, magicString})
        Dim combinedHash As String = getMD5Hash(emailPasswordCombination)

        Return combinedHash
    End Function
    Private Shared Function getMD5Hash(ByVal strToHash As String) As String
        Dim md5Obj As Security.Cryptography.MD5CryptoServiceProvider
        Dim bytesToHash() As Byte
        Dim strResult As String = String.Empty

        md5Obj = New Security.Cryptography.MD5CryptoServiceProvider
        bytesToHash = System.Text.Encoding.ASCII.GetBytes(strToHash)

        bytesToHash = md5Obj.ComputeHash(bytesToHash)

        For Each b As Byte In bytesToHash
            strResult += b.ToString("x2", System.Globalization.CultureInfo.CurrentCulture)
        Next
        Return strResult
    End Function

    ''' <summary>
    ''' Returns the userlist
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetUserList() As GetUserListResponse
        Dim retVal As GetUserListResponse
        Dim connector As WBSAPIConnector

        connector = New WBSAPIConnector
        retVal = connector.GetAccountUsers(m_emailAddress, m_computedHash)
        connector = Nothing

        Return retVal
    End Function

    ''' <summary>
    ''' Returns an withingsusers after setting public
    ''' </summary>
    ''' <param name="userID">the users id</param>
    ''' <exception cref="System.ArgumentNullException">if parameter userId is null or empty</exception>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetUserById(ByVal userId As Integer) As User
        Dim userRequest As GetUserListResponse
        Dim userList() As User
        Dim retVal As User = Nothing
        Dim result As IEnumerable(Of User)

        If userId <= 0 Then _
            Throw New ArgumentNullException("userId")

        userRequest = Me.GetUserList
        userList = userRequest.Users
        If userRequest.Status = StatusResponseEnum.Successfull Then
            result = From x As User In userList _
                      Where x.UserId = userId

            If result.Count > 0 Then
                retVal = result.First
            End If

        Else
            Return Nothing
        End If
        userList = Nothing
        result = Nothing

        Return retVal
    End Function

    ''' <summary>
    ''' Creates a new Withings Body Metrics Service Connector.
    ''' </summary>
    ''' <param name="emailAddress">Users Emailadress for Login</param>
    ''' <param name="password">Users password for Login - will be stored as secure string</param>
    ''' <exception cref="System.ArgumentNullException">if one parameter is null or empty</exception>
    ''' <remarks></remarks>
    Public Sub New(ByVal emailAddress As String, ByVal password As String)
        If String.IsNullOrEmpty(emailAddress) Then _
            Throw New ArgumentNullException("emailAddress")

        If String.IsNullOrEmpty(password) Then _
            Throw New ArgumentNullException("password")

        m_emailAddress = emailAddress
        m_password = password

        m_computedHash = Me.ComputeHash
    End Sub

End Class
